# -*- coding: utf-8 -*-
import logging
import re
import datetime
import time

from django.conf import settings

from api.account.model import *
from api.coupon import handler as coupon_handler
from api.preset.handler import get_fixed_bucket
from async.async_job import send_authcode
from common.account.db.account import get_financial_accounts
from common.cache import account as cache
from common.utils import exceptions as err
from common.utils.api import mask_string
from common.utils.id_generator import generate_auth_code
from common.utils.respcode import StatusCode
from common.coupon.db import check_register_coupon
from common.prize.db import set_fresh_award
from common.coupon.model import CouponTemplate, SOURCE_TYPE
from common.utils.tz import get_utc_date, to_ts
from common.black_account.db import list_type_account
from common.black_account.model import WITHDRAW_BLACK_TYPE

COUNTRY_CODE_DCT = {
    'cn': '86',
}

_LOGGER = logging.getLogger("bigbang")


def get_fixed_num(phone, country=None):
    if not country:
        country = settings.COUNTRY
    prefix = COUNTRY_CODE_DCT[country.lower()]
    phone = prefix + phone

    return phone


def send_auth_code(phone, country=None, ip='', need_check=True):
    if need_check:
        if ip and not cache.check_ip_count(ip):
            return None
        if not cache.check_phone_count(phone):
            return None
    code = cache.get_auth_code(phone)
    if not code:
        code = generate_auth_code()
        cache.save_auth_code(phone, code)
    else:
        ttl = cache.get_auth_code_ttl(phone)
        if int(ttl) > 120:
            # raise err.DataError(u'发送短信验证码太频繁，请稍后再试。')
            _LOGGER.warn('send_auth_code fail for ttl, %s %s', phone, ttl)
            return code
    try:
        send_authcode(phone, code, country)
        _LOGGER.info('send sms succ, ip:%s, phone:%s, code: %s', ip, phone, code)
    except Exception as e:
        cache.delete_auth_code(phone)
        raise e
    return code


def check_auth_code(phone, code):
    try:
        code = str(code)
    except UnicodeEncodeError:
        raise err.ParamError(status=StatusCode.ILLEGAL_STRING)
    if not phone:
        return False
    saved_code = cache.get_auth_code(phone)
    _LOGGER.info('saved_code: %s, code: %s' % (saved_code, code))
    return str(saved_code) == str(code)  # or code == '12345678'


def delete_auth_code(phone):
    cache.delete_auth_code(phone)


def get_personal_info(user):
    info = PersonalInfo(user)
    info.phone = info.phone[2:] if info.phone else None
    if info.avatar:
        info.avatar = get_fixed_bucket(info.avatar, bucket='avatar')
    if re.match(r'\d{13}', info.user_name) and info.user_name.startswith('86'):
        info.user_name = mask_string(info.user_name[2:])
    financial_accounts = []
    for item in get_financial_accounts(user['id']):
        financial_accounts.append(item.as_dict())
    info.update({
        'financial_accounts': financial_accounts
    })
    return info


def add_fresh_coupon(user_id):
    # 新老注册活动互斥
    id_rank = [item.id for item in CouponTemplate.query.filter(CouponTemplate.source_type == SOURCE_TYPE.NEW_USER)]
    id_new_rank = [item.id for item in CouponTemplate.query.filter(CouponTemplate.source_type == SOURCE_TYPE.REGISTER)]
    if check_register_coupon(id_rank[0], user_id):
        set_fresh_award(user_id, fresh_type='old_fresh_award')
        return
    if check_register_coupon(id_new_rank[0], user_id):
        set_fresh_award(user_id, fresh_type='fresh_award')
        return
    count = 1
    for tid in id_rank:
        coupon_handler.send_coupon_to_user(user_id, tid, count, coupon_from=u'新用户注册')
    set_fresh_award(user_id, fresh_type='old_fresh_award')
    _LOGGER.info('send old_register_award to {} finished'.format(user_id))


def add_new_fresh_coupon(user_id):
    # 7天红包, 同时设置已发送新手活动红包
    id_rank = [item.id for item in CouponTemplate.query.filter(CouponTemplate.source_type == SOURCE_TYPE.NEW_USER)]
    id_new_rank = [item.id for item in CouponTemplate.query.filter(CouponTemplate.source_type == SOURCE_TYPE.REGISTER)]
    if check_register_coupon(id_rank[0], user_id):
        set_fresh_award(user_id, fresh_type='old_fresh_award')
        return
    if check_register_coupon(id_new_rank[0], user_id):
        set_fresh_award(user_id, fresh_type='fresh_award')
        return
    from_txt = u'新用户注册活动'
    start = to_ts(get_utc_date())  # base on time zone
    count = 0
    for t_id in id_new_rank:
        offset = count / 2
        start_ts = offset * 3600 * 24 + start
        coupon_handler.send_coupon_to_user(user_id, t_id, 1, start_ts=start_ts, coupon_from=from_txt)
        count += 1
    set_fresh_award(user_id, fresh_type='fresh_award')
    _LOGGER.info('send fresh_register_award to {} successfully'.format(user_id))


def check_black_ip_equip(black_type, black_account):
    if black_type == 'IP':
        black_account_ip = list_type_account(WITHDRAW_BLACK_TYPE.BLACK_IP)
        if black_account in black_account_ip:
            raise err.ParamError('account_ip in withdraw black account')
    if black_type == 'equip':
        black_account_equip = list_type_account(WITHDRAW_BLACK_TYPE.BLACK_EQUIPMENT)
        if black_account in black_account_equip:
            raise err.ParamError('account equipment_id in withdraw black account')